package com.desehou.fristspring.controller;

import com.desehou.fristspring.model.JsonResult;
import com.desehou.fristspring.model.StatusCode;
import com.desehou.fristspring.model.User;
import com.desehou.fristspring.service.UserService;
import org.springframework.http.HttpHeaders;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

@RestController
public class UserController {

    @Resource(name = "userServiceImpl")
    private UserService userService;


    @RequestMapping("/person")
    public User selectById(Integer userId) {
        return userService.selectById(userId);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonResult selectByMobeleAndPsw(String mobile, String password) {
        return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage(), userService.selectByMobeleAndPsw(mobile, DigestUtils.md5DigestAsHex(password.getBytes())));
    }

    @RequestMapping("/user")
    public JsonResult users() {
        return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage(), userService.users());
    }

    @RequestMapping("/user/nickname")
    public JsonResult editNickName(Integer userId, String nickName) {

        if (userService.editNickNameById(userId, nickName)) {

            return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage(), null);
        } else {
            return new JsonResult(StatusCode.FAIL_EDIT_NICK_NAME.getCode(), StatusCode.FAIL_EDIT_NICK_NAME.getMessage(), null);
        }

    }

    @RequestMapping("/center")
    public User selectByToken(@RequestHeader HttpHeaders headers) {

        System.out.print(headers);

        return null;
    }

    @RequestMapping("/register")
    public JsonResult register(String mobile, String password, String nickName, String realName, String userName) {

        UUID uuid = UUID.randomUUID();
        String authenticateToken = uuid.toString();

        if (userService.register(mobile, DigestUtils.md5DigestAsHex(password.getBytes()), nickName, realName, userName, authenticateToken)) {

            return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage(), null);
        } else {
            return new JsonResult(StatusCode.FAIL_REGISTER.getCode(), StatusCode.FAIL_REGISTER.getMessage(), null);
        }

    }


}
